/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.repair.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.repair.entity.*;
import org.springblade.modules.repair.service.*;
import org.springblade.modules.repair.vo.MalFunctionHistoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 故障工单明细 控制器
 *
 * @author zcc
 * @since 2021-05-21
 */
@RestController
@AllArgsConstructor
@RequestMapping("repair/maintain/malfunction/history")
@Api(value = "故障维修历史记录", tags = "故障维修历史记录")
public class MaintainMalfunctionHistoryController extends BladeController {

	private final IMaintainMalfunctionHistoryService maintainMalfunctionHistoryService;
	private final MaintainMalfunctionRecordService malfunctionRecordService;
	private final MaintainCheckRecordService maintainCheckRecordService;
	private final IWxFaultTypeService wxFaultTypeService;
	private final IWxFaultCauseService wxFaultCauseService;

	/**
	 * 批量新增
	 *
	 * @param list 数据集
	 * @return 状态
	 */
	@PostMapping("/saveBatch")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "批量新增", notes = "list")
	public R saveBatch(@Valid @RequestBody List<MaintainMalfunctionHistory> list) {

		return R.data(maintainMalfunctionHistoryService.saveBatch(list));
	}

	/**
	 * 新增 故障工单明细
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "单个新增", notes = "one")
	public R saveOne(@Valid @RequestBody MaintainMalfunctionHistory maintainMalfunctionHistory) {
		maintainMalfunctionHistoryService.saveOrUpdate(maintainMalfunctionHistory);
		return R.data(maintainMalfunctionHistory.getId());
	}

	/**
	 * 删除 通过操作记录id
	 */
	@DeleteMapping("/remove")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "多个删除", notes = "one")
	public R remove(@RequestParam String ids) {
		return R.status(maintainMalfunctionHistoryService.removeByIds(Func.toLongList(ids)));
	}

	/**
	 * 修改 故障工单明细
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "修改", notes = "list")
	public R update(@Valid @RequestBody List<MaintainMalfunctionHistory> list) {
		return R.status(maintainMalfunctionHistoryService.updateBatchById(list));
	}

	/**
	 * 修改 故障工单明细
	 */
	@PostMapping("/update/of/planId")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "根据计划id修改维修类型")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "planId", value = "任务id", required = true, dataType = "String"),
		@ApiImplicitParam(name = "status", value = "状态1：设备检修 2：部件更换", required = true),
		@ApiImplicitParam(name = "groupId", value = "作业Id", required = true)
	})
	public R updateByPlanId(@RequestParam("planId") String planId, @RequestParam("status") Integer status, @RequestParam("groupId") Long groupId) {

		List<MaintainMalfunctionHistory> list = maintainMalfunctionHistoryService.list(Wrappers.<MaintainMalfunctionHistory>lambdaQuery().eq(MaintainMalfunctionHistory::getPlanId, planId));
		list.forEach(o -> o.setStatus(status));
		return R.status(maintainMalfunctionHistoryService.updateBatchById(list));
	}


	@GetMapping("/delete")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "删除")
	public R delete(@RequestParam("planId") Long planId, @RequestParam("checkContentId") Long checkContentId) {
		return R.data(maintainMalfunctionHistoryService.deleteBatch(planId, checkContentId));
	}


	@GetMapping("/detail")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "详情")
	public R detail(@RequestParam("planId") Long planId) {
		List<MalFunctionHistoryVO> malFunctionHistoryVOS = maintainMalfunctionHistoryService.selectByPlanId(planId);
		return R.data(malFunctionHistoryVOS);
	}

	@GetMapping("/detail/v2")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "详情")
	public R detailV2(Long id) {
		MaintainMalfunctionHistory malfunctionHistory = maintainMalfunctionHistoryService.getById(id);

		Map<Long, List<WxFaultType>> wxFaultTypeMap = wxFaultTypeService.list().stream().collect(Collectors.groupingBy(WxFaultType::getId));
		Map<Long, List<WxFaultCause>> wxFaultCauseMap = wxFaultCauseService.list().stream().collect(Collectors.groupingBy(WxFaultCause::getId));
		if (StrUtil.isNotEmpty(malfunctionHistory.getFaultReasonKey())) {
			List<String> wxFaultIds = Func.toStrList(malfunctionHistory.getFaultReasonKey());
			List<String> names1 = new ArrayList<>(16);
			if (wxFaultIds != null && wxFaultIds.size() > 0) {
				for (String wxFaultId : wxFaultIds) {
					List<WxFaultCause> wxFaultCauses = wxFaultCauseMap.get(Convert.toLong(wxFaultId));
					if (wxFaultCauses != null && wxFaultCauses.size() > 0) {
						names1.add(wxFaultCauses.get(0).getFaultName());
					}
				}
				if (names1.contains("其他")) {
					names1.remove("其他");
					names1.add("其他");
					malfunctionHistory.setFaultReasonName(String.join(",", names1) + "-" + malfunctionHistory.getFaultReasonName());
				} else {
					malfunctionHistory.setFaultReasonName(String.join(",", names1));
				}
			}
		}

		if (StrUtil.isNotEmpty(malfunctionHistory.getFaultReasonWhoKey())) {
			List<String> wxTypeIds = Func.toStrList(malfunctionHistory.getFaultReasonWhoKey());
			List<String> names2 = new ArrayList<>(16);
			if (wxTypeIds != null && wxTypeIds.size() > 0) {
				for (String wxTypeId : wxTypeIds) {
					List<WxFaultType> wxFaultTypes = wxFaultTypeMap.get(Convert.toLong(wxTypeId));
					if (wxFaultTypes != null && wxFaultTypes.size() > 0) {
						names2.add(wxFaultTypes.get(0).getName());
					}
				}
				if (names2.contains("其他")) {
					names2.remove("其他");
					names2.add("其他");
					malfunctionHistory.setFaultReasonWhoName(String.join(",", names2) + "-" + malfunctionHistory.getFaultReasonWhoName());
				} else {
					malfunctionHistory.setFaultReasonWhoName(String.join(",", names2));
				}
			}
		}

		return R.data(malfunctionHistory);
	}

	/**
	 * 新增维修历史操作记录
	 *
	 * @param maintainMalfunctionRecord
	 * @return
	 */
	@PostMapping("/save/record")
	public R<Boolean> saveRecord(@RequestBody MaintainMalfunctionRecord maintainMalfunctionRecord) {
		return R.data(malfunctionRecordService.save(maintainMalfunctionRecord));
	}

}
